'''
根据接口自动生成测试脚本

思路：
1. 读取接口模块文件，如task_wlkt.py
2. 根据 `def XXX ` 关键字，获取接口名称
    例如：
        def assign_task(para):
            response = requests.post(
                url=RunConfig.url + "/wt/task/assign",
                headers=RunConfig.headers,
                json=para,
                verify=False
                )
            return response
3. 对每一个接口在指定路径下生成对应的测试脚本
    脚本格式：
        @pytest.mark.parametrize("description,data,expection", read_json(case_path + "assign_task.json"))
        def test_assign_task(self, description, data, expection):
            log.info("测试用例：{}".format(description))
            log.info("测试数据：{}".format(data))
            assign_res = task_wlkt.assign_task(data)
            log.info("返回结果：{}".format(assign_res.json()))
            common_assert(assign_res, expection)
'''
import re


def extract_function_name(signature):
    '''
    根据函数签名提取函数名
    :param signature:
    :return:
    '''
    pattern = r'\s*def\s+([a-zA-Z0-9_]*)\s*\('
    match = re.match(pattern, signature)
    if match:
        return match.group(1)
    else:
        return None


api_names = []
def read_apis(api_file_path):
    with open(api_file_path, 'r', encoding='utf-8') as f:
        for line in f.readlines():
            if "def" in line:
                method_name = extract_function_name(line)
                api_names.append(method_name)


def write_scripts(file_path):
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write("import os\n")
        f.write("import pytest\n")
        f.write("from apis.wlkt import task_wlkt\n")
        f.write("from config import RunConfig\n")
        f.write("from utils.common_tools import common_assert\n")
        f.write("from utils.get_logger import GetLog\n")
        f.write("from utils.raed_json import read_json\n")
        f.write("\n")
        f.write("log = GetLog.get_logger()\n")
        f.write("\n")
        f.write("\n")
        f.write("class TestTaskWlkt:\n")
        f.write("    case_path  = (RunConfig.BASE_PATH +\n")
        f.write("                         os.sep + \"data\" +\n")
        f.write("                         os.sep + \"single\" +\n")
        f.write("                         os.sep + \"wlkt\" +\n")
        f.write("                         os.sep + \"wlkt_task_controller\" +\n")
        f.write("                         os.sep)")
        for api in api_names:
            f.write('\n\n')
            f.write(f'\t@pytest.mark.parametrize("description,data,expection", read_json(case_path + "{api}.json"))\n')
            f.write('\tdef test_assign_task(self, description, data, expection):\n')
            f.write('\t    log.info("测试用例：{{}}".format(description))\n')
            f.write('\t    log.info("测试数据：{{}}".format(data))\n')
            f.write(f'\t    assign_res = task_wlkt.{api}(data)\n')
            f.write('\t    log.info("返回结果：{{}}".format(assign_res.json()))\n')
            f.write('\t    common_assert(assign_res, expection)\n')


if __name__ == '__main__':
    apis_path = "../apis/wlkt/wt_task_controller.py"
    scripts_path = "../test_dir/test_single_api/test_wlkt/demo.py"
    read_apis(apis_path)
    print(api_names)
    write_scripts(scripts_path)
    print("执行完成")